package cn.yedong.org.service.impl;

import cn.yedong.basic.exception.BusinessException;
import cn.yedong.basic.util.BaiduAiUtils;
import cn.yedong.basic.util.Md5Utils;
import cn.yedong.basic.util.StrUtils;
import cn.yedong.org.domain.Employee;
import cn.yedong.org.domain.Shop;
import cn.yedong.org.domain.ShopAuditLog;
import cn.yedong.org.mapper.EmployeeMapper;
import cn.yedong.org.mapper.ShopAuditLogMapper;
import cn.yedong.org.mapper.ShopMapper;
import cn.yedong.org.obj.ShopDbj;
import cn.yedong.org.service.IShopService;
import cn.yedong.basic.service.impl.BaseServiceImpl;
import cn.yedong.user.domain.Logininfo;
import cn.yedong.user.mapper.LogininfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
     * 店铺注册的业务
     * @param shop
     */
    @Override
    @Transactional
    public void settlement(Shop shop) {
        //一：校验
        //1.空值校验
        if(StringUtils.isEmpty(shop.getName()) || StringUtils.isEmpty(shop.getTel())){
            throw new BusinessException("信息不能为空！");
        }
        //2.两次密码不一致校验
        if(!shop.getAdmin().getComfirmPassword().equals(shop.getAdmin().getPassword())){
            throw new BusinessException("两次密码不一致！");
        }
        //3.当前店铺是否入住过校验
        Shop dbShop = shopMapper.findByNameAndAddress(shop);
        if(dbShop != null){//数据库有当前店铺
            throw new BusinessException("该店铺已经入驻，请直接登陆！如果忘记密码，请联系管理员！！");
        }
        //二：百度AI智能审核【店铺名，log是否合法】
        if(!BaiduAiUtils.TextCensor(shop.getName())){
            throw new BusinessException("店铺名不合规，请重新输入！！");
        }
        if(!BaiduAiUtils.ImgCensor("http://123.207.27.208"+shop.getLogo())){
            throw new BusinessException("店铺logo不合规，请重新上传！！");
        }

        //三：添加到数据库
        //1.先添加店长信息
        Employee admin = shop.getAdmin();//从shop.admin中获取前端注册的店长信息

        //【添加店长信息之前-需要先添加logininfo-并且将其自增id设置回店长的shopId】
        //处理密码和盐值
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(admin.getPassword() + salt);
        admin.setSalt(salt);
        admin.setPassword(md5Pwd);
        //保存logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(admin,logininfo);
        logininfo.setType(0);//后台注册：管理员
        logininfo.setDisable(true);
        logininfoMapper.add(logininfo);
        //将logininfo的自增id设置给admin的logininfoId
        admin.setLogininfo_id(logininfo.getId());
        employeeMapper.add(admin);//修改添加的xml三个属性，添加店长时，返回店长的自增id

        //【添加店铺信息之前，将店长的自增id设置进店铺；添加完店铺，再将店铺的自增id更新到店长】
        //2.再添加店铺信息
        shop.setAdminId(admin.getId());//添加店铺前，将店长id设置到shop
        shopMapper.add(shop);//添加shop
        //3.将店铺id更新到员工表中
        admin.setShop_id(shop.getId());//添加店铺之后，将店铺的自增长id添加到店长shop_id字段
        employeeMapper.update(admin);//更新店长信息
    }

    /**
     * 店铺审核通过
     * @param log
     */
    @Transactional
    @Override
    public void auditPass(ShopAuditLog log) throws MessagingException {
        //1.修改状态
        shopMapper.updateState(2,log.getShopId());
        //2.添加审核日志
        log.setState(1);//审核通过
        log.setAuditId(350L);
        shopAuditLogMapper.add(log);
        //3.审核通过向店长发送激活邮件
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("974431480@qq.com");
        helper.setSubject("店铺审核成功通知");
        //根据日志的shopID查询店铺
        Shop shop = shopMapper.loadById(log.getShopId());
        //true - 能够再内容中编写html标签 - 会解析
        helper.setText("<h1>【宠物之家】您的店铺已注册成功!</h1><img src='http://123.207.27.208"+shop.getLogo()+"' >" +
                "<a href='http://127.0.0.1:8080/shop/active/"+log.getShopId()+"'>请点击该链接激活!</a>",true);
        //根据店铺的AdminId查询收件人
        Employee employee = employeeMapper.loadById(shop.getAdminId());
        //设置收件人
        helper.setTo(employee.getEmail());
        javaMailSender.send(mimeMessage);
    }

    /**
     * 店铺审核失败
     * @param log
     */
    @Transactional
    @Override
    public void auditReject(ShopAuditLog log) {
        //1.修改状态
        shopMapper.updateState(4,log.getShopId());

        //2.添加审核日志
        log.setState(0);//审核失败
        log.setAuditId(350L);
        shopAuditLogMapper.add(log);

        //3.审核通过向店长邮件重新提交信息
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("974431480@qq.com");
        message.setSubject("店铺审核失败通知");
        message.setText("抱歉，您的店铺审核失败！请重新提交有效信息！");
        //根据日志的shopID查询店铺
        Shop shop = shopMapper.loadById(log.getShopId());
        //查询收件人
        Employee employee = employeeMapper.loadById(shop.getAdminId());
        //设置收件人
        message.setTo(employee.getEmail());
        javaMailSender.send(message);
    }

    /**
     * 激活店铺
     * @param id
     */
    @Override
    @Transactional
    public void active(Long id) {
        //1.修改店铺状态：正常使用
        shopMapper.updateState(3,id);
        //2.添加审核日志
        ShopAuditLog shopAuditLog = new ShopAuditLog();
        //审核状态：1   表示通过
        shopAuditLog.setState(1);
        //设置店铺id
        shopAuditLog.setShopId(id);
        //设置审核人
        shopAuditLog.setAuditId(350L);
        //设置审核备注
        shopAuditLog.setNote("店铺激活成功！");
        //将日志添加到数据库
        shopAuditLogMapper.add(shopAuditLog);
        //3.修改店长状态
        //根据店铺id查询到shop
        Shop shop = shopMapper.loadById(id);
        //根据店铺管理员id查询到员工(店长)信息
        Employee employee = employeeMapper.loadById(shop.getAdminId());
        //激活成功-将店长状态设置为1；默认0，禁用
        employee.setState(1);
        //设置完状态，更新店长信息
        employeeMapper.update(employee);
        //发送邮件？
    }

    /**
     * 获取echart数据：店铺状态数据
     * @return
     */
    @Override
    public List<ShopDbj> echart() {
        return shopMapper.echart();
    }
}
